package com.example.cpop.controller;

import com.example.cpop.mapper.UserMapper;
import com.example.cpop.model.User;
import com.example.cpop.tools.Constant;
import com.example.cpop.tools.ResponseBodyMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: fzykd
 * Date: 2022-10-15
 * Time: 14:14
 */
//tools工具类


@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private User userLogin;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;


    @RequestMapping("/login1")
    public ResponseBodyMessage login1(@RequestParam String username, @RequestParam String password,
                                     HttpServletRequest request){

        userLogin.setUsername(username);
        userLogin.setPassword(password);

        User user = userMapper.login(userLogin);

        if (user == null){
            return new ResponseBodyMessage<>(-1,"登录失败",userLogin);
        }else {
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            return new ResponseBodyMessage<>(0,"登录成功",userLogin);
        }

    }


    @RequestMapping("/login")
    //前端传来的参数
    public ResponseBodyMessage login(@RequestParam String username, @RequestParam String password,
                                      HttpServletRequest request){

        //传来的参数 与数据库返回的的数据对比
        User user = userMapper.selectByName(username);
        //如果没有查到传回的就是null
        if (user == null){
            System.out.println("登陆失败");
            //返回个前端数据 将要返回的数据 封装好 封装成一个泛型
           return new ResponseBodyMessage<>(-1,"用户名或密码错误",user);
        }else {
            //如果找了这个用户名 那么将用户名的密码 和 数据库加密的密码比对 相同那么就登录成功 后面的参数是 数据库中的加密密码
            //matches 对比两个密码是否相同
            boolean flg = bCryptPasswordEncoder.matches(password,user.getPassword());
            if (!flg){
                return new ResponseBodyMessage<>(-1,"用户名或密码错误",user);
            }
            //创建session 两步写成一步 key:value 将key封装一下 好写不易错
            request.getSession().setAttribute(Constant.USERINFO_SESSION_KEY,user);
            System.out.println(user.toString());
            return new ResponseBodyMessage<>(0,"登录成功",user);
        }

    }
}
